package com.ruoyi.web.controller.api.city;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.druid.support.json.JSONUtils;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.model.CityLoginUser;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.file.MimeTypeUtils;
import com.ruoyi.cust.domain.CityUser;
import com.ruoyi.cust.service.ICityUserService;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.web.core.utils.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.Valid;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Api("登录")
@RequestMapping({"/api/city/login"})
@RestController
/* loaded from: CityLoginController.class */ public class CityLoginController extends BaseController {
    public static final String WX_SESSION_ID = "wx_session_id";
    @Autowired
    StringRedisTemplate redisTemplate;
    @Autowired
    private TokenService     tokenService;
    @Autowired
    private ICityUserService iCityUserService;
    @Autowired
    private ICityUserService cityUserService;
    @Value("${weixin.appid}")
    private String           appid;
    @Value("${weixin.secret}")
    private String           secret;

    @ApiOperation("根据ID获取用户")
    @GetMapping({"/getUser"})
    public CityUser getInfo(@RequestParam("userId") String openid) {
        CityUser cityUser = new CityUser();
        cityUser.setOpenid(openid);
        cityUser.setUserType(0);
        return this.cityUserService.selectCityUserList(cityUser).get(0);
    }

    @ApiOperation("编辑用户")
    @PostMapping({"/updateUser"})
    public AjaxResult edit(@RequestBody @Valid CityUser cityUser, BindingResult bindingResult) {
        return toAjax(this.cityUserService.updateCityUser(cityUser));
    }

    @ApiOperation("更新用户头像")
    @PostMapping({"/avatar"})
    public AjaxResult avatar(@RequestParam("avatarfile") MultipartFile file, @RequestParam("userId") Long userId) throws Exception {
        String avatar = "";
        if (!file.isEmpty()) {
            FileUploadUtils.assertAllowed(file, MimeTypeUtils.IMAGE_EXTENSION);
            avatar = OSSUtil.uploadFile2(file);
            System.out.println(avatar);
            CityUser cityUser = new CityUser();
            cityUser.setUserId(userId);
            cityUser.setAvatar(avatar);
            this.cityUserService.updateCityUser(cityUser);
        }
        return success(avatar);
    }

    @ApiOperation("获取用户sessionId")
    @GetMapping({"/getSessionId"})
    public Map<String, Object> getSessionId(@RequestParam("code") String code) {
        System.out.println(code);
        Map<String, Object> map    = new HashMap<>();
        String              result = HttpUtil.get(" https://api.weixin.qq.com/sns/jscode2session?appid=" + this.appid + "&secret=" + this.secret + "&js_code=" + code + "&grant_type=authorization_code");
        System.out.println(result);
        if (JSONUtil.parseObj(result).get("openid") != null) {
            map.put("openid", JSONUtil.parseObj(result).getStr("openid"));
        }
        if (JSONUtil.parseObj(result).get("session_key") != null) {
            map.put("session_key", JSONUtil.parseObj(result).getStr("session_key"));
        }
        if (JSONUtil.parseObj(result).get("unionid") != null) {
            map.put("unionid", JSONUtil.parseObj(result).getStr("unionid"));
        }
        if (JSONUtil.parseObj(result).get("errcode") != null) {
            map.put("errcode", JSONUtil.parseObj(result).getStr("errcode"));
        }
        if (JSONUtil.parseObj(result).get("errmsg") != null) {
            map.put("errmsg", JSONUtil.parseObj(result).getStr("errmsg"));
        }
        System.out.println(result);
        String s = UUID.randomUUID().toString();
        this.redisTemplate.opsForValue().set(WX_SESSION_ID + s, result);
        map.put("sessionId", s);
        return map;
    }

    @ApiOperation("用户手机验证码登陆")
    @GetMapping({"/phoneNumberLogin"})
    public Map<String, Object> phoneNumberLogin(@RequestParam("code") String code, @RequestParam("phoneNumber") String phoneNumber) throws ParseException {
        System.out.println(code);
        Map<String, Object> map    = new HashMap<>();
        String              result = HttpUtil.get(" https://api.weixin.qq.com/sns/jscode2session?appid=" + this.appid + "&secret=" + this.secret + "&js_code=" + code + "&grant_type=authorization_code");
        System.out.println(result);
        CityLoginUser cityLoginUser = new CityLoginUser();
        CityUser      cityUser      = new CityUser();
        if (JSONUtil.parseObj(result).get("openid") != null) {
            cityUser.setOpenid(JSONUtil.parseObj(result).getStr("openid"));
        }
        Long userId = Long.valueOf(IdUtil.getSnowflake(1, 1).nextId());
        System.out.println("userId" + userId);
        cityUser.setUserId(userId);
        cityUser.setStatus(0);
        cityUser.setNickName(phoneNumber);
        cityUser.setPhonenumber(phoneNumber);
        cityUser.setCity("");
        cityUser.setAvatar("/city_images/2023/08/15/a4038249117f8b198f9698874e28def_20230815121626A002.png");
        cityUser.setCountry("中国");
        cityUser.setLanguage("zh_CN");
        cityUser.setLoginIp(cityLoginUser.getIpaddr());
        cityUser.setLoginLocation(cityLoginUser.getLoginLocation());
        cityUser.setLoginDate(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())));
        CityUser cityUser2 = new CityUser();
        cityUser2.setPhonenumber(cityUser.getPhonenumber());
        List<CityUser> cityUsers = this.iCityUserService.selectCityUserList(cityUser2);
        if (cityUsers == null) {
            cityUser2 = new CityUser();
            cityUser2.setOpenid(cityUser.getOpenid());
            if (this.iCityUserService.selectCityUserList(cityUser2) != null) {
                return error();
            }
            cityUser.setCreateTime(new Date());
            this.iCityUserService.insertCityUser(cityUser);
        }
        else if (!cityUser.getOpenid().equals(cityUsers.get(0).getOpenid())) {
            return error();
        }
        else {
            CityUser cityUserDB = cityUsers.get(0);
            cityUser.setUserId(cityUserDB.getUserId());
            cityUser.setAvatar(cityUserDB.getAvatar());
            cityUserDB.setLoginIp(cityLoginUser.getIpaddr());
            cityUserDB.setLoginLocation(cityLoginUser.getLoginLocation());
            this.iCityUserService.updateCityUser(cityUserDB);
        }
        cityLoginUser.setUserId(cityUser.getUserId());
        String token = this.tokenService.createToken(cityLoginUser);
        cityUser.setToken(token);
        map.put("state", true);
        map.put(Constants.TOKEN, token);
        map.put("userId", cityUser.getUserId().toString());
        map.put(Constants.JWT_AVATAR, cityUser.getAvatar());
        map.put("name", cityUser.getNickName());
        return map;
    }

    @ApiOperation("获取用户手机号码")
    @GetMapping({"/getPhoneNumber"})
    public String getCode(@RequestParam("code") String code) throws ParseException {
        System.out.println(code);
        new HashMap();
        String result2     = HttpUtil.get("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + this.appid + "&secret=" + this.secret);
        String accessToken = "";
        if (JSONUtil.parseObj(result2).get("access_token") != null) {
            accessToken = JSONUtil.parseObj(result2).get("access_token").toString();
        }
        System.out.println("access_token:" + accessToken);
        JSONObject jsonCode = new JSONObject();
        jsonCode.put(AjaxResult.CODE_TAG, code);
        String resPhone    = HttpUtil.post("https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=" + accessToken, jsonCode.toString());
        String phoneNumber = "";
        if (!StringUtils.isEmpty(resPhone) || resPhone.contains("phone_info") || resPhone.contains("phoneNumber")) {
            phoneNumber = JSON.parseObject(resPhone).getJSONObject("phone_info").get("phoneNumber").toString();
        }
        return phoneNumber;
    }

    @ApiOperation("微信登陆")
    @PostMapping({"/wxlogin"})
    public Map<String, Object> wxlogin(@RequestBody WxAuth wxAuth) {
        Map<String, Object> map = new HashMap<>();
        try {
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (StrUtil.isBlank(wxAuth.getOpenid())) {
            map.put("state", false);
            return map;
        }
        String wxRes = wxDecrypt(wxAuth.getEncryptedData(), wxAuth.getSessionId(), wxAuth.getIv());
        System.out.println("用户信息：" + wxRes);
        if (wxRes == null) {
            map.put("state", false);
        }
        else {
            WxUserInfo    wxUserInfo    = JSON.parseObject(wxRes, WxUserInfo.class);
            CityLoginUser cityLoginUser = new CityLoginUser();
            CityUser      cityUser      = new CityUser();
            cityUser.setOpenid(wxAuth.getOpenid());
            cityUser.setUserId(Long.valueOf(IdUtil.getSnowflake(1, 1).nextId()));
            String name = StringUtils.isEmpty(wxUserInfo.getNickName())? "微信用户": wxUserInfo.getNickName();
            cityUser.setUserName(name);
            cityUser.setNickName(name);
            String token = this.tokenService.createToken(cityLoginUser);
            cityUser.setUserId(Long.valueOf(IdUtil.getSnowflake(1, 1).nextId()));
            cityUser.setToken(token);
            cityUser.setStatus(1);
            cityUser.setAvatar("/city_images/2023/08/15/a4038249117f8b198f9698874e28def_20230815121626A002.png");
            cityUser.setCity(wxUserInfo.getCity());
            cityUser.setCountry(wxUserInfo.getCountry());
            cityUser.setLanguage(wxUserInfo.getLanguage());
            cityUser.setProvince(wxUserInfo.getProvince());
            cityUser.setNickName(wxUserInfo.getNickName());
            cityUser.setLoginIp(cityLoginUser.getIpaddr());
            cityUser.setLoginLocation(cityLoginUser.getLoginLocation());
            cityUser.setLoginDate(new Date(cityLoginUser.getLoginTime()));
            //            QueryWrapper queryWrapper = new QueryWrapper();
            //            queryWrapper.eq("openid", cityUser.getOpenid());
            //            CityUser cityUserDB = this.iCityUserService.getOne(queryWrapper);

            CityUser cityUser2 = new CityUser();
            cityUser2.setOpenid(cityUser.getOpenid());
            List<CityUser> cityUsers = this.iCityUserService.selectCityUserList(cityUser2);
            if (cityUsers != null) {
                CityUser cityUserDB = cityUsers.get(0);
                cityUser.setUserId(cityUserDB.getUserId());
                BeanUtil.copyProperties(cityUser, cityUserDB);
                this.iCityUserService.updateCityUser(cityUserDB);
            }
            else {
                cityUser.setCreateTime(new Date());
                this.iCityUserService.insertCityUser(cityUser);
            }
            map.put("state", true);
            map.put(Constants.TOKEN, token);
            map.put("userId", cityUser.getUserId().toString());
            map.put(Constants.JWT_AVATAR, cityUser.getAvatar());
            map.put("name", cityUser.getNickName());
        }
        return map;
    }

    private String wxDecrypt(String encryptedData, String sessionId, String vi) {
        try {
            String json = this.redisTemplate.opsForValue().get(WX_SESSION_ID + sessionId);
            System.out.println("之前存储在redis中的信息：" + json);
            System.out.println("encryptedData：" + encryptedData);
            System.out.println("vi：" + vi);
            return WeChatUtil.wxDecrypt(encryptedData, (String) JSON.parseObject(json).get("session_key"), vi);
        } catch (Exception e) {
            return null;
        }
    }
}
